package com.pet.article.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.pet.article.feign.*;
import com.pet.article.mapper.ApArticleConfigMapper;
import com.pet.article.mapper.ApArticleContentMapper;
import com.pet.article.mapper.ApArticleMapper;
import com.pet.article.mapper.ApAuthorMapper;
import com.pet.article.service.ApArticleService;
import com.pet.article.service.ApCollectionService;
import com.pet.common.constants.article.ArticleConstans;
import com.pet.common.exception.LeadNewsException;
import com.pet.model.admin.pojos.AdChannel;
import com.pet.model.article.dtos.ApArticleVo;
import com.pet.model.article.dtos.ArticleHomeDto;
import com.pet.model.article.pojos.ApArticle;
import com.pet.model.article.pojos.ArticleVisitStreamMsg;
import com.pet.model.common.dtos.ResponseResult;
import com.pet.model.common.enums.AppHttpCodeEnum;
import com.pet.model.constants.RedisConstants;
import com.pet.model.user.pojos.ApUser;
import com.pet.utils.common.BeanHelper;
import com.pet.utils.common.JsonUtils;
import com.pet.utils.threadlocal.ThreadLocalUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Transactional
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    // 单页最大加载的数字
    private final static short MAX_PAGE_SIZE = 50;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Value("${fdfs.url}")
    private String fileServerUrl;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private ApBehaviorEntryFeign apBehaviorEntryFeign;
    @Autowired
    private ApCollectionService apCollectionService;
    @Autowired
    private ApUnlikesBehaviorFeign apUnlikesBehaviorFeign;
    @Autowired
    private ApLikesBehaviorFeign apLikesBehaviorFeign;
    @Autowired
    private ApUserFollowFeign apUserFollowFeign;
    @Autowired
    private ApAuthorMapper apAuthorMapper;
    @Autowired
    private AdChannelFeign adChannelFeign;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public ResponseResult load(Short loadType, ArticleHomeDto dto) {
        //1.校验参数
        Integer size = dto.getSize();
        if(size == null || size == 0){
            size = 100;
        }
        size = Math.min(size,MAX_PAGE_SIZE);
        dto.setSize(size);

        //类型参数检验
        if(!loadType.equals(ArticleConstans.LOADTYPE_LOAD_MORE)&&!loadType.equals(ArticleConstans.LOADTYPE_LOAD_NEW)){
            loadType = ArticleConstans.LOADTYPE_LOAD_MORE;
        }
        //文章频道校验
        if(StringUtils.isEmpty(dto.getTag())){
            dto.setTag(ArticleConstans.DEFAULT_TAG);
        }

        //时间校验
        if(dto.getMaxBehotTime() == null) dto.setMaxBehotTime(new Date());
        if(dto.getMinBehotTime() == null) dto.setMinBehotTime(new Date());
        //查询数据
        //先查询rides
        if(!Strings.isNullOrEmpty( dto.getTag())&&  !dto.getTag().equals(ArticleConstans.DEFAULT_TAG)) {
            //1）取出当前频道redis缓存
            String channelDateCache = redisTemplate.opsForValue().get(RedisConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if(!Strings.isNullOrEmpty(channelDateCache)) {
                List<ApArticleVo> articleVos = JsonUtils.nativeRead(channelDateCache, new TypeReference<List<ApArticleVo>>() {
                });
                if (CollectionUtils.isNotEmpty(articleVos)) {

                    ResponseResult responseResult = ResponseResult.okResult(articleVos);
                    responseResult.setHost(fileServerUrl);
                    return responseResult;
                }else {
                    List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadType);
                    if(CollectionUtils.isNotEmpty(apArticles)) {
                        //缓存redis
                        //计算分值存到redis
                        apArticles.forEach(a -> a.setScore(computeScore(a)));
                        redisTemplate.opsForValue().set(RedisConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag(), JsonUtils.toString(apArticles));
                        apArticles.sort(((o1, o2) -> o2.getScore().compareTo(o1.getScore())));
                    }
                    ResponseResult responseResult = ResponseResult.okResult(apArticles);
                    responseResult.setHost(fileServerUrl);
                    return responseResult;
                }
            }else {
                List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadType);
                if(CollectionUtils.isNotEmpty(apArticles)) {
                    //缓存redis
                    //计算分值存到redis
                    apArticles.forEach(a -> a.setScore(computeScore(a)));
                    redisTemplate.opsForValue().set(RedisConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag(), JsonUtils.toString(apArticles));
                    apArticles.sort(((o1, o2) -> o2.getScore().compareTo(o1.getScore())));
                }
                ResponseResult responseResult = ResponseResult.okResult(apArticles);
                responseResult.setHost(fileServerUrl);
                return responseResult;
            }
        }else {
            String dateCache = redisTemplate.opsForValue().get(RedisConstants.HOT_ARTICLE_FIRST_PAGE + RedisConstants.DEFAULT_TAG);
            if(!Strings.isNullOrEmpty(dateCache)) {
                List<ApArticleVo> articleVos = JsonUtils.nativeRead(dateCache, new TypeReference<List<ApArticleVo>>() {
                });
                if (CollectionUtils.isNotEmpty(articleVos)) {

                    ResponseResult responseResult = ResponseResult.okResult(articleVos);
                    responseResult.setHost(fileServerUrl);
                    return responseResult;
                }else {
                    List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadType);
                    if(CollectionUtils.isNotEmpty(apArticles)) {
                        //计算分值存到redis
                        apArticles.forEach(a -> a.setScore(computeScore(a)));
                        redisTemplate.opsForValue().set(RedisConstants.HOT_ARTICLE_FIRST_PAGE + RedisConstants.DEFAULT_TAG, JsonUtils.toString(apArticles));
                        apArticles.sort(((o1, o2) -> o2.getScore().compareTo(o1.getScore())));
                    }
                    ResponseResult responseResult = ResponseResult.okResult(apArticles);
                    responseResult.setHost(fileServerUrl);
                    return responseResult;
                }
            } else {
                List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadType);
                if(CollectionUtils.isNotEmpty(apArticles)) {
                    //计算分值存到redis
                    apArticles.forEach(a -> a.setScore(computeScore(a)));
                    redisTemplate.opsForValue().set(RedisConstants.HOT_ARTICLE_FIRST_PAGE + RedisConstants.DEFAULT_TAG, JsonUtils.toString(apArticles));
                    apArticles.sort(((o1, o2) -> o2.getScore().compareTo(o1.getScore())));
                }
                ResponseResult responseResult = ResponseResult.okResult(apArticles);
                responseResult.setHost(fileServerUrl);
                return responseResult;
            }
        }
        //redis缓存没数据，在查询数据库
    }

    @Override
    public ResponseResult loadlabel(Short loadType, ArticleHomeDto dto) {
        //1.校验参数
        Integer size = dto.getSize();
        if(size == null || size == 0){
            size = 10;
        }
        size = Math.min(size,MAX_PAGE_SIZE);
        dto.setSize(size);
        ApUser apUser = (ApUser) ThreadLocalUtils.get();
        dto.setUserId(apUser.getId());

        //时间校验
        if(dto.getMaxBehotTime() == null) dto.setMaxBehotTime(new Date());
        if(dto.getMinBehotTime() == null) dto.setMinBehotTime(new Date());
        List<ApArticle> apArticles = apArticleMapper.loadlabel(dto, loadType);

        //结果封装
        ResponseResult responseResult = ResponseResult.okResult(apArticles);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult loadNew(Short loadType, ArticleHomeDto dto) {
        //1.校验参数
        Integer size = dto.getSize();
        if(size == null || size == 0){
            size = 10;
        }
        size = Math.min(size,MAX_PAGE_SIZE);
        dto.setSize(size);

        //文章频道校验
        if(StringUtils.isEmpty(dto.getTag())){
            dto.setTag(ArticleConstans.DEFAULT_TAG);
        }

        //时间校验
        if(dto.getMaxBehotTime() == null) dto.setMaxBehotTime(new Date());
        if(dto.getMinBehotTime() == null) dto.setMinBehotTime(new Date());
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadType);

        //结果封装
        ResponseResult responseResult = ResponseResult.okResult(apArticles);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public void updateArticle(ArticleVisitStreamMsg streamMsg) {
        ApArticle apArticle = apArticleMapper.selectById(streamMsg.getArticleId());
        //1.查询当前文章是否存在
        if(apArticle==null){
            throw new LeadNewsException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2.获取流式计算的统计值，更新文章行为数据
        if(streamMsg.getView()!=null){
            apArticle.setViews(apArticle.getViews()+streamMsg.getView().intValue());
        }
        if(streamMsg.getLike()!=null){
            apArticle.setLikes(apArticle.getLikes()+streamMsg.getLike().intValue());
        }
        if(streamMsg.getComment()!=null){
            apArticle.setComment(apArticle.getComment()+streamMsg.getComment().intValue());
        }
        if(streamMsg.getCollect()!=null){
            apArticle.setCollection(apArticle.getCollection()+streamMsg.getCollect().intValue());
        }

        //3.更新文章数据
        updateById(apArticle);

        //4.计算当前文章的分值
        Integer score = computeScore(apArticle);

        //5.更新每个频道的redis缓存数据
        //1）取出当前频道redis缓存
        String channelDateCache = redisTemplate.opsForValue().get(RedisConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());
        //2）更新当前频道redis缓存
        updateRedisCache(channelDateCache,apArticle,score,false);

        //6.更新推荐频道的redis缓存数据
        //1）取出推荐频道redis缓存
        String dateCache = redisTemplate.opsForValue().get(RedisConstants.HOT_ARTICLE_FIRST_PAGE + RedisConstants.DEFAULT_TAG);
        //2）更新推荐频道的缓存
        updateRedisCache(dateCache,apArticle,score,true);
    }

    /**
     * 更新redis的热点文章缓存数据
     * @param dateCache
     * @param apArticle
     * @param score
     */
    private void updateRedisCache(String dateCache, ApArticle apArticle, Integer score, boolean isAll) {
        if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(dateCache)){
            //转换成List集合
            List<ApArticleVo> articleVos = JsonUtils.nativeRead(dateCache, new TypeReference<List<ApArticleVo>>() {});
            boolean flag = false;
            //判断当前操作的文章是否在缓存中，如果在的话，直接修改分值和行为数
            for (ApArticleVo articleVo : articleVos) {
                if(apArticle.getId().equals(articleVo.getId())){
                    //修改分值和行为数
                    articleVo.setScore(score);
                    articleVo.setCollection(apArticle.getCollection());
                    articleVo.setLikes(apArticle.getLikes());
                    articleVo.setViews(apArticle.getViews());
                    articleVo.setComment(apArticle.getComment());
                    flag=true;
                    break;
                }
            }
            //如果当前缓存列表没有当前文章
            if(!flag){
                //直接把当前文章追加到最后
                ApArticleVo apArticleVo = BeanHelper.copyProperties(apArticle, ApArticleVo.class);
                apArticleVo.setScore(score);
                articleVos.add(apArticleVo);
            }
            //重新再存入redis缓存
            String key = null;
            if(isAll){
                key = RedisConstants.HOT_ARTICLE_FIRST_PAGE+RedisConstants.DEFAULT_TAG;
            }else {
                key = RedisConstants.HOT_ARTICLE_FIRST_PAGE+apArticle.getChannelId();
            }
            sortAndCachToRedis(articleVos,key);
        }
    }

    /**
     * 缓存到redis数据
     * @param articleVos
     */
    private void sortAndCachToRedis(List<ApArticleVo> articleVos, String key) {
        //1）按照文章分值倒序
        articleVos.sort(((o1, o2) -> o2.getScore().compareTo(o1.getScore())));
        //2）如果数量大于30，截取前30条
        if(articleVos.size()>30){
            articleVos=articleVos.subList(0,30);
        }
        //3）缓存文章到redis
        redisTemplate.opsForValue().set(key, JsonUtils.toString(articleVos));

    }

    /**
     * 计算所有文章的分值
     * @param apArticleVoList
     * @return
     */
    private List<ApArticleVo> computeArticles(List<ApArticle> apArticleVoList) {
        List<ApArticleVo> list = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(apArticleVoList)){
            apArticleVoList.forEach(apArticle -> {
                //拷贝数据
                ApArticleVo apArticleVo = BeanHelper.copyProperties(apArticle, ApArticleVo.class);
                //计算文章的分值
                Integer score = computeScore(apArticle);
                apArticleVo.setScore(score);
                list.add(apArticleVo);
            });
        }
        return list;
    }

    /**
     * 计算每篇文章的分值
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if(apArticle.getViews()!=null){
            score +=apArticle.getViews();
        }
        if(apArticle.getLikes()!=null){
            score +=apArticle.getLikes()* ArticleConstans.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(apArticle.getCollection()!=null){
            score+=apArticle.getCollection()*ArticleConstans.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        if(apArticle.getComment()!=null){
            score+=apArticle.getComment()*ArticleConstans.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        return score;
    }

    /**
     * 查询指定前几天的文章
     * @param date 天数
     * @return
     */
    private List<ApArticle> getApArticleByPubDate(int date) {
        //查询当前日期前5天的日期
        String beforeDate = DateTime.now().minusDays(date).toString("yyyy-MM-dd 00:00:00");
        QueryWrapper<ApArticle> queryWrapper = new QueryWrapper<>();
        queryWrapper.gt("publish_time",beforeDate);
        List<ApArticle> apArticleList = apArticleMapper.selectList(queryWrapper);
        return apArticleList;
    }

    @Override
    public void saveToRedis() {
        //1.查询当前时间的前5天的文章
        List<ApArticle> apArticleVoList = getApArticleByPubDate(5);
        //2.计算所有文章的分值
        List<ApArticleVo>articleVoList = computeArticles(apArticleVoList);
        //3.查询文章的所有频道
        List<AdChannel> channelList = adChannelFeign.findAll().getData();

        //4.按照文章的频道，分别过滤出分值较高的前30条，保存到redis数据库
        if(CollectionUtils.isNotEmpty(channelList)){
            channelList.forEach(adChannel -> {
                //1）按照频道分别从articleVoList筛选出文章
                List<ApArticleVo> articleVos = articleVoList.stream().filter(articleVo ->articleVo.getChannelId().equals(adChannel.getId())).collect(Collectors.toList());
                //缓存redis
                String key = RedisConstants.HOT_ARTICLE_FIRST_PAGE + adChannel.getId();

                sortAndCachToRedis(articleVos,key);
            });
        }
        //为推荐频道存储所有文章分值高的前30条
        String key = RedisConstants.HOT_ARTICLE_FIRST_PAGE + RedisConstants.DEFAULT_TAG;

        sortAndCachToRedis(articleVoList,key);
    }

    @Override
    public ResponseResult search(ArticleHomeDto dto) {
        ArrayList<ApArticle> list = Lists.newArrayList();
        if(StringUtils.isNotEmpty(dto.getTitle())){
             list = apArticleMapper.search(dto.getTitle());
        }
        ResponseResult responseResult = ResponseResult.okResult(list);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }
}